package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private TaskService taskService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public InputStream processImg(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        Long bpmninfoId = carPackageAudit.getBpmninfoId();
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(bpmninfoId);

        List<String> list = new ArrayList<>();
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            // 审核中 添加高亮参数
                // 获取当前任务节点(方法参数是 流程实例id)
            list = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        }else {
            // 非审核中 不添加
            list = Collections.emptyList();
        }

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .singleResult();

        // 第2个参数是高亮参数
        ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        InputStream inputStream = processDiagramGenerator.generateDiagram(repositoryService.getBpmnModel(processDefinition.getId())
                , list,
                Collections.emptyList(),
                "宋体", "宋体", "宋体"
        );
        return inputStream;
    }

    @Override
    @Transactional
    public void cancelApply(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        // 非审核中状态不能撤销
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("非法操作");
        }

        // 修改bus_car_package_audit流程实例表
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);

        // 修改服务单项表 审核状态初始化
        serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);

        // 删除流程实例
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"delete");
    }

    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        // 非审核中状态报错
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("非法操作");
        }

        // 完成任务节点(注入流程变量(通过/不通过))
        Map<String,Object> map = new HashMap<>();
        map.put("auditStatus",auditStatus);
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        taskService.complete(task.getId(),map);

        // 通过
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (nextTask != null) {
                // 有下一个节点
                // 修改 流程实例表 审批意见info、审核时间auditTime、审核人auditorId
                carPackageAudit.setAuditorId(Long.valueOf(nextTask.getAssignee()));
                carPackageAudit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
            }else {
                // 没下一个节点
                // 修改 流程实例表 审批意见info、审核状态status→审核通过、审核时间auditTime
                carPackageAudit.setStatus(auditStatus);
                // 修改 服务单项审核状态 审核通过
                serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }
            carPackageAudit.setInfo(carPackageAudit.getInfo() + "<->" + ShiroUtils.getUser().getUserName() + "通过审核 审核意见为:" + info);
        }else {
            // 不通过
            // 修改 流程实例表 审批意见info、审核状态status→审核拒绝、审核时间auditTime
            carPackageAudit.setInfo(carPackageAudit.getInfo() + "<->" + ShiroUtils.getUser().getUserName() + "不通过审核 审核意见为:" + info);
            carPackageAudit.setStatus(auditStatus);
            // 修改 服务单项审核状态 重新调整
            serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        }
        carPackageAudit.setAuditTime(new Date());
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}
